package com.wzy.vx.controller;

import com.wzy.vx.dataobject.ProductCategory;
import com.wzy.vx.exception.SellException;
import com.wzy.vx.form.CategoryForm;
import com.wzy.vx.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import javax.xml.ws.Action;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: vx
 * @Package: com.wzy.vx.controller
 * @ClassName: SellerCategoryController
 * @Author: Administrator
 * @Description: ${description}
 * @Date: 2019/3/20 11:33
 * @Version: 1.0
 */
@Controller
@RequestMapping("/seller/category")
public class SellerCategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("list")
    public ModelAndView list(Map<String,Object> map) {
        List<ProductCategory> categories = categoryService.findAll();
        map.put("categoryList",categories);
        return new ModelAndView("category/list",map);
    }

    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "categoryId",required = false) Integer categoryId,
                              Map<String,Object> map) {
        if (categoryId != null){
            ProductCategory productCategory = categoryService.findOne(categoryId);
            map.put("category",productCategory);
        }
        return new ModelAndView("category/index",map);
    }

    /**
     * 保存类目
     * */
    @PostMapping("/save")
    public ModelAndView save(@Valid CategoryForm categoryForm,
                             BindingResult bindResult,
                             Map<String,Object> map) {
        if (bindResult.hasErrors()){
            map.put("msg",bindResult.getFieldError().getDefaultMessage());
            map.put("url","/sell/seller/category/index");
        }
        ProductCategory productCategory = new ProductCategory();
        try{
             if (categoryForm.getCategoryId() != null){
            productCategory = categoryService.findOne(categoryForm.getCategoryId());
             }
            BeanUtils.copyProperties(categoryForm,productCategory);
            categoryService.save(productCategory);
        }catch (SellException e){
            map.put("msg",e.getMessage());
            map.put("url","/sell/seller/category/list");
            return new ModelAndView("common/error",map);
        }
       map.put("url","/sell/seller/category/list");
        return new ModelAndView("common/success",map);
    }





}
